<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item>信息流管理</el-breadcrumb-item>
      <el-breadcrumb-item>结算单管理</el-breadcrumb-item>
    </el-breadcrumb>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item>信息流管理</el-breadcrumb-item>
      <el-breadcrumb-item>
        <span
          class="u-cursor"
          @click="$router.push({
            name: 'flow-invoice',
          })"
        >账号管理</span>
      </el-breadcrumb-item>
      <el-breadcrumb-item>
        <span
          class="u-cursor"
          @click="$router.back()"
        >{{pageTitle}}开票</span>
      </el-breadcrumb-item>
      <el-breadcrumb-item>选择结算单</el-breadcrumb-item>
    </el-breadcrumb>

    <Container class="u-mb15">
      <!-- 筛选 -->
      <el-form
        inline
        class="m-form--filter"
      >
      <el-form-item label-width="0">
        <el-alert
          class="u-w500"
          type="warning"
          :closable="false"
          v-if="['create', 'edit'].includes(pageAction)"
        >
          1、已选的结算单数据已被清空！必须重新选择结算单！否则无结算单数据 <br>
          2、必须筛选客户全称！如不筛选，则无数据 <br>
          3、结算周期筛选:开始日期≤数据的结算周期开始日期；结束日期≥数据的结算周期结束日期；数据才可被筛选出 <br>
          例如：筛选日期2020.01.01-2020.01.30，那么结算周期 2020.01.10-2020.01.20数据可以被筛选出；结算周期 2020.01.01-2020.02.01数据不可被筛选出 <br>
          4、发票状态‘未设置’的发票可以选择开票
        </el-alert>
      </el-form-item>
      <br>
        <el-form-item>
          <el-select
            class="u-w160"
            size="mini"
            filterable
            placeholder="请选择客户名称"
            v-model="filter.customerId"
          >
            <el-option
              v-for="item in customerOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-date-picker
            class="u-w330"
            size="mini"
            v-model="dateValue"
            type="daterange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="dateChange"
            format="yyyy/MM/dd"
            :clearable="false"
            :picker-options="$store.state.PICKER_OPTIONS"
          >
          </el-date-picker> 
        </el-form-item>
        <el-form-item>
          <el-select
            class="u-w200"
            size="mini"
            filterable
            multiple
            collapse-tags
            placeholder="请选择全部结算方式"
            v-model="filter.settleWay"
          >
            <el-option
              v-for="item in SETTLEWAY"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select
           class="u-w200"
            size="mini"
            filterable
            multiple
            collapse-tags
            placeholder="请选择发票状态"
            v-model="filter.invoiceStatus"
          >
            <el-option
              v-for="item in INVOICESTATEDATA"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            size="mini"
            @click="search"
          >查询</el-button>
        </el-form-item>
      </el-form>
    </Container>

    <Container>
      <!-- 表格 -->
      <el-table
        border
        stripe
        :data="tableData"
        ref="multipleTable"
        empty-text="暂无数据，请先筛选客户全称"
        @selection-change="changeTableSelection"
      >
        <el-table-column
          type="selection"
          width="35"
          fixed
          :selectable="handleSelectable"
        >
        </el-table-column>
        <el-table-column
          align="center"
          v-for="(item, index) in filterTableColumn"
          :label="item.label"
          :key="index"
        >
          <template slot-scope="scope">
            
            <!-- 结算周期 -->
            <template v-if="item.rederStatus">{{ scope.row[item.reder[0]] +'-'+ scope.row[item.reder[1]] }}</template>
            <!-- 结算方式 -->
            <template v-else-if="item.prop === 'settleWay'">{{ mapOptionLabel(SETTLEWAY,scope.row.settleWay) }}</template>
            <!-- 发票状态 -->
            <template v-else-if="item.prop === 'invoiceStatus'">{{ mapOptionLabel(INVOICESTATEDATA,scope.row.invoiceStatus) }}</template>

            <!-- <template v-else-if="item.prop === 'settlementAmount'">{{scope.row.settlementAmount == null ? 0 : scope.row.settlementAmount}}</template> -->
            <!-- 其他 -->
            <template v-else>{{scope.row[item.prop]}}</template>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          width="100"
        >
          <template slot-scope="scope">
            <el-button
              type="text"
              @click="$router.push({
                name: 'flow-statements-detail',
                query: {
                  action: 'detail',
                  id: scope.row.billId
                }
              })"
            >查看</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        background
        :page-sizes="[50, 100, 500, 1000]"
        :page-size="page.pageSize"
        layout="total, prev, pager, next, sizes"
        :total="pageTotal"
        @size-change="handlePagerSizeChange"
        @current-change="handlePagerCurrentChange"
      />
    </Container>
    <Affix :offset-bottom="0">
      <ButtonGroup
        isFixed
        align="right"
      >
        <el-button
          size="small"
          type="primary"
          v-if="['create', 'edit'].includes(pageAction)"
          @click="handleClickSure"
        >确定</el-button>
      </ButtonGroup>
    </Affix>
  <!-- 导入 -->
  <el-dialog
    title="提示"
    :visible.sync="importVisible"
    width="850">
    <!-- <div>导入成功数据：{{importData.success}}条</div> -->
    <span slot="footer" class="dialog-footer">
      <el-button @click="importVisible = false">取 消</el-button>
      <el-button type="primary" @click="importVisible = false">确 定</el-button>
    </span>
  </el-dialog>
  </div>
</template>

<script>
import Container from "@/components/container";
import ButtonGroup from "@/components/button-group";
import Affix from "@/components/affix";
import { SETTLEWAY, INVOICESTATEDATA } from "@/assets/js/flow-option";
import { mapOptionLabel,mapOptionValue } from "@/util";
import { exportExcel } from '@/utils/fileDown.js'

export default {
  name: "flow-accountdata",
  components: {
    Container,
    Affix,
    ButtonGroup
  },
  data() {
    return {
      SETTLEWAY,
      INVOICESTATEDATA,
      BASE_URL: process.env.VUE_APP_BASE_URL,
      fileList:[],
      pageAction: this.$route.query.action,
      // 下拉
      dateValue:Number(this.$route.query.dataValue)|| null,
      customerOptions: [],
      // 筛选
      filter: {
        startDate:'',
        endDate:'',
        billId: Number(this.$route.query.StateData) || null,
        invoiceStatus: Number(this.$route.query.invoiceStatus) || null,
        customerId: Number(this.$route.query.customerId) || null,
        settleWay: Number(this.$route.query.settleWay) || null
      },
      //导入
      importVisible:false,
      importData:null,

      tableData: [],
      tableSelectionData: [],
      tableColumn: [
        {
          label: "结算单号",
          prop: "billId",
          visible: true
        },
        {
          label: "结算周期",
          prop: "startDate",
          rederStatus:true,
          reder:['startDate','endDate'],
          visible: true
        },
        {
          label: "客户全称",
          prop: "customerFullName",
          visible: true
        },
        {
          label: "结算方式",
          prop: "settleWay",
          visible: true
        },
        {
          label: "实际结算金额（元）",
          prop: "settlementAmount",
          visible: true
        },
        {
          label: "发票状态",
          prop: "invoiceStatus",
          visible: true
        }
      ],
      page: {
        pageNo: 1,
        pageSize: 50
      },
      pageTotal: 0,
      statementIds:this.$route.query.statementIds||null,
      // id:this.$route.query.id||null,
    };
  },
  computed: {
    pageTitle() {
      return {
        create: "新增",
        edit: "编辑",
        detail: "查看"
      }[this.pageAction];
    },
    filterTableColumn() {
      return this.tableColumn.filter(item => item.visible);
    },
    requestSearch() {
      return {
        ...this.filter,
        ...this.page,
        invoiceStatus:this.filter.invoiceStatus == null || this.filter.invoiceStatus.length == 0 ? null : this.filter.invoiceStatus.join(),
        settleWay:this.filter.settleWay == null || this.filter.settleWay == 0 ? null : this.filter.settleWay.join()
      };
    }
  },
  updated () {
  // 在这里调用toggleSelection选中方法
    this.toggleSelection(this.tableData)
  },
  methods: {
    contractUpload(res) {
      if (res.code === 0) {
        this.importVisible = true;
        this.importData = res.data;
      } else {
        this.$message({
          type: "error",
          message: res.msg
        });
      }
      this.importLoading.close();
      this.getTable()
    },
    contractBeforeUpload(file) {
      const type = /\.xlsx?$/.test(file.name);
      if (!type) {
        this.$message.error("请上传excel格式的文件");
      }
      this.importLoading = this.$loading({
        lock: true,
        text: "正在导入...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      return type;
    },
    // 导出业务清单
    exportExcel() {
      exportExcel('/manage/api/bus/statements/export',this.requestSearch)
    },
    dateChange() {
      this.filter.startDate = this.formatDateTime(this.dateValue[0], "y-m-d");
      this.filter.endDate = this.formatDateTime(this.dateValue[1], "y-m-d");
    },
    mapOptionLabel,
    // 下拉
    fetchCustomerOptions() {
      this.$http({
        method: "get",
        url: "/manage/api/bus/customer/get_customer_full_name",
        params: {
          status: 0
        }
      }).then(res => {
        if (res.data.code === 0) {
          this.customerOptions = res.data.data
          if (this.$route.query.customerId) {
            this.filter.customerId = Number(this.$route.query.customerId);
          }
        }
      });
    },
    // 列表
    search() {
      this.page.pageNo = 1;
      this.getTable();
    },
    //获取列表
    getTable() {
      this.$http({
        method: "post",
        url: "/manage/api/bus/statements/get_list",
        data: this.requestSearch
      }).then(res => {
        if (res.data.code === 0) {
          let data = res.data.data;
          this.tableData = data.list;
          this.pageTotal = data.listCount;
        } else {
          this.$message.error(res.data.msg);
        }
      });
    },
    handleClickSure(){
      // let customerFullNameId = this.tableData.length > 0 ? this.tableData[0].customerFullNameId : []
      // let oCustomerFullNameId =this.statementIds ? this.tableData[0].customerFullNameId : null
      this.$router.push({
        name: 'flow-invoice-detail',
        query: {
          action: this.pageAction,
          statementIds:this.statementIds,
          customerFullNameId: this.statementIds ? this.tableData[0].customerFullNameId : null
        }
      })
    },
    //判断选择框是否可选
    handleSelectable(row) {
      return row.invoiceStatus > 1 ? false :true ;
    },
    toggleSelection (rows) {
      if(this.statementIds==null || ''){return}
      let ids = this.statementIds.split(',')
      let tableId = [] // b
      rows.forEach(res=>{                  //把表格里所有的id加入到b里
          tableId.push(res.billId.toString())
      })
      for(let i = 0;i<tableId.length;i++){                 //对b循环  如果b里面有a（a是被选中的行） 则把索引代入到first函数里 让这些行的复选框选中
        if(tableId.indexOf(ids[i])>=0){
            this.first([rows[tableId.indexOf(ids[i])]])
        }
      }
      
    },
    first(rows){
      this.$nextTick(()=>{
          rows.forEach(row => {
              this.$refs.multipleTable.toggleRowSelection(row,true);
          });
      })
    },
    changeTableSelection(data) {
      if(data){
        // this.id = this.mapOptionValue(this.customerOptions,data[0].customerFullName)
      }
      this.statementIds = data.map(item => item.billId).join()
      this.tableSelectionData = data;
      
    },
    mapOptionValue(data, name) {
      let item = data.find(item => item.name === name);
      if (item) {
        return item.id;
      }
      return "-";
    },
    handlePagerSizeChange(v) {
      this.page.pageSize = v;
      this.getTable();
    },
    handlePagerCurrentChange(v) {
      this.page.pageNo = v;
      this.getTable();
    }
  },
  created() {
    this.fetchCustomerOptions();
    if(this.filter.customerId != null){
      this.getTable();
    }
    
  }
};
</script>